<?php

namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;
use PHPExcel;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;

class Richangbaoxiao extends Commonwork
{
	public function shenpisave(){
		$request = Request::instance();$data = $request->post();
		//print_r($data);
		$aid=$data["aid"];
		if($aid){
			if(isset($data["pizhun"])){
				if(count($data["pizhun"])){
					Db::startTrans();
					try{
						for($i=0;$i<count($data["pizhun"]["did"]);$i++){
							if($data["pizhun"]["pifu"][$i]>$data["pizhun"]["feis"][$i]){
								return json_encode(["msg"=>"批复金额不得超过申请金额","state"=>2]);
							}
						}
						for($i=0;$i<count($data["pizhun"]["did"]);$i++){
							$up["id"]=$data["pizhun"]["did"][$i];
							$up["pizhunfeiyong"]=$data["pizhun"]["pifu"][$i];
							$up["state"]=$data["pizhun"]["state"][$up["id"]];
							Db::table("rc_baoxiao_detail")->update($up);
							$where["did"]=$data["pizhun"]["did"][$i];
							$where["aid"]=$aid;
							$upy["jine"]=$data["pizhun"]["pifu"][$i];
							Db::table("yusuan_detail")->where($where)->update($upy);
						}
						Db::table("rc_baoxiao_apply")->query("update rc_baoxiao_apply as a set a.pizhunjin=(select sum(ad.pizhunfeiyong) from rc_baoxiao_detail as ad where ad.aid=a.id)");

					}catch (\Exception $e){
						Db::rollBack();
						return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
					}
					Db::commit();
					return json_encode(["msg"=>"","state"=>1]);
				}else{
					return json_encode(["msg"=>"请正确提交","state"=>2]);
				}
				
			}else{
				return json_encode(["msg"=>"请正确提交","state"=>2]);
			}
		}else{
			return json_encode(["msg"=>"请正确提交","state"=>2]);
		}
	}
	public function shenhedetail($myId,$trackId,$workId){
		$workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $aid=$workfloawde["yw_id"];
		$this->assign("aid",$aid);
		$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
		//print_r($apply);
		$apply["cman"]=Db::table("employee")->where(["id"=>$apply["cuser"]])->value("em_name");
		$apply["ctime"]=date("Y-m-d",$apply["ctime"]);
		$tmp=Db::table("cg_kaoheqi2")->alias("k2")
		->join("cg_kaoheqi1 k1","k2.pid=k1.id")
		->join("cg_cainian c","k1.cid=c.id")
		->where("k2.id={$apply["kaohe"]}")
		->field("c.title as nian,k2.title as yue")->find();

		$apply["kaohe"]=$tmp["nian"].'-'.$tmp["yue"];
		$apply["payway"]=Db::table("cg_paymethod")->where(["id"=>$apply["payway"]])->value("title");
		$apply["bman"]=Db::table("employee")->where(["id"=>$apply["baoxiaoren"]])->value("em_name");
		$apply["jrbm"]=Db::table("department")->where("id={$apply["jrbm"]}")->value("de_name");
		$apply["weifujin"]=$apply["pizhunjin"]-$apply["zhifujin"];
		if($apply["feis"])
			$feiyong=Db::table("cg_feiyongkemu3")->where("id in ({$apply["feis"]})")->select();
		else
			$feiyong=[];
		$this->assign("feiyong",$feiyong);
		$feiyongnum=count($feiyong);
		$this->assign("feiyongnum",$feiyongnum);
		if($apply["chuchai"]){
			
			$apply["chuchai"]=Db::table("chuchai_apply")->where("id in ({$apply["chuchai"]})")->select();
		}
		if($apply["wanneng"]){
			
			$apply["wanneng"]=Db::table("wanneng_apply")->where("id in ({$apply["wanneng"]})")->select();
		}
		$this->assign("apply",$apply);
		$applyde=Db::table("rc_baoxiao_detail")->alias("apd")
		->join("cg_jxs j","apd.jxs=j.id","LEFT")
		->join("employee e","apd.shenpiren=e.id","LEFT")
		->where(["aid"=>$aid])
		->field("apd.id,apd.start,apd.end,apd.chufa,apd.mudi,apd.feiid,apd.feis,apd.pizhunfeiyong,apd.remark,j.title as jxs,e.em_name,apd.state")
		->select();
		
		$this->assign("applyde",$applyde);
		$fujian=[];
			//print_r($apply);
			if($apply["fujian"]){
				$fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
				//print_r($fujian);
			}
		$this->assign("fujian",$fujian);
		///支付
		$zhifu=Db::table("rc_baoxiao_pay")->alias("ap")
		->join("employee c","ap.cuser=c.id")
		->join("employee p","ap.zfuser=p.id")
		->where(["ap.aid"=>$aid])
		->field("c.em_name as cu,p.em_name as pu,ap.ctime,ap.zftime,ap.pzno,ap.jine,ap.remark")
		->select();
		for($i=0;$i<count($zhifu);$i++){
			$zhifu[$i]["ctime"]=date("Y-m-d",$zhifu[$i]["ctime"]);
			$zhifu[$i]["zftime"]=date("Y-m-d",$zhifu[$i]["zftime"]);
		}
		$this->assign("zhifu",$zhifu);
		 $logs=$this->getlog(10,$aid);
            //print_r($logs);
            $this->assign("logs",$logs);
		return $this->fetch();
	}
	public function shenhe($myId,$trackId,$workId){
		$workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $aid=$workfloawde["yw_id"];
        $apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
        if($apply["state"]==2){
        	 $this->redirect('Richangbaoxiao/zuofei', ['aid' => $aid,"from"=>2]);
        }else{
        	$apply["cman"]=Db::table("employee")->where(["id"=>$apply["cuser"]])->value("em_name");
        	$apply["cdep"]=Db::table("department")->alias("d")->join("department_employee de","de.department_id=d.id")->where(["de.employee_id"=>$apply["cuser"],"de.index"=>1])->value("d.de_name");
        	//计算申请时间
			$cha=time()-$apply["ctime"];
			$apply["day"]=floor($cha/24/3600);
			$cha=$cha-$apply["day"]*24*3600;
			$apply["hour"]=floor($cha/3600);
			$cha=$cha-$apply["hour"]*3600;
			$apply["fen"]=floor($cha/60);
			$apply["ctime"]=date("Y-m-d",$apply["ctime"]);
			$tmp=Db::table("cg_kaoheqi2")->alias("k2")
			->join("cg_kaoheqi1 k1","k2.pid=k1.id")
			->join("cg_cainian c","k1.cid=c.id")
			->where("k2.id={$apply["kaohe"]}")
			->field("c.title as nian,k2.title as yue")->find();

			$apply["kaohe"]=$tmp["nian"].'-'.$tmp["yue"];
			$apply["payway"]=Db::table("cg_paymethod")->where(["id"=>$apply["payway"]])->value("title");
			$apply["bman"]=Db::table("employee")->where(["id"=>$apply["baoxiaoren"]])->value("em_name");
			$apply["bdep"]=Db::table("department")->alias("d")->join("department_employee de","de.department_id=d.id")->where(["de.employee_id"=>$apply["baoxiaoren"],"de.index"=>1])->value("d.de_name");
			$apply["jrbm"]=Db::table("department")->where("id={$apply["jrbm"]}")->value("de_name");
			$feiyong=Db::table("cg_feiyongkemu3")->where("id in ({$apply["feis"]})")->select();

			$this->assign("feiyong",$feiyong);
			$feiyongnum=count($feiyong);
			$this->assign("feiyongnum",$feiyongnum);
			if($apply["chuchai"]){
			
				$apply["chuchai"]=Db::table("chuchai_apply")->where("id in ({$apply["chuchai"]})")->select();
			}
			if($apply["wanneng"]){
				
				$apply["wanneng"]=Db::table("wanneng_apply")->where("id in ({$apply["wanneng"]})")->select();
			}
			$this->assign("apply",$apply);
			$detail=Db::table("rc_baoxiao_detail")->alias("apd")
			->join("cg_feiyongkemu3 k3","apd.feiid=k3.id")
			->where("apd.aid=$aid")
			->field("apd.id,apd.feiid,k3.title as kemu3,apd.pizhunfeiyong,apd.state")
			->select();
			$this->assign("detail",$detail);

			$yusuan=Db::table("yusuan_detail")->alias("yd")
			->join("rc_baoxiao_detail apd","yd.did=apd.id")
			->join("yusuan y","y.id=yd.yid")
			->join("cg_feiyongkemu3 k3","apd.feiid=k3.id")
			->where("yd.aid=$aid")->group("yd.yid")
			->field("yd.yid,k3.title,sum(yd.jine) as benci,y.jine as zong")
			->select();
			$lamp=1;
			$ally["zong"]=0;
			$ally["yiyong"]=0;
			$ally["shenqing"]=0;
			$ally["weiyong"]=0;
			for($i=0;$i<count($yusuan);$i++){
				$ally["zong"]+=$yusuan[$i]["zong"];
				$yusuan[$i]["pifu"]=Db::table("yusuan_detail")->where("type=2 and yid={$yusuan[$i]["yid"]}")->sum("jine");
				if(!$yusuan[$i]["pifu"])
					$yusuan[$i]["pifu"]=0;
				$ally["yiyong"]+=$yusuan[$i]["pifu"];
				$yusuan[$i]["weiyong"]=$yusuan[$i]["zong"]-$yusuan[$i]["pifu"];
				if($yusuan[$i]["weiyong"]<0){
					$lamp=3;
				}
				$yusuan[$i]["shenqing"]=Db::table("yusuan_detail")->where("type=1 and yid={$yusuan[$i]["yid"]}")->sum("jine");
				if(!$yusuan[$i]["shenqing"])
					$yusuan[$i]["shenqing"]=0;
				if($yusuan[$i]["weiyong"]-$yusuan[$i]["shenqing"]<0&&$lamp<2)
					$lamp=2;
				$ally["shenqing"]+=$yusuan[$i]["shenqing"];
				$ally["weiyong"]+=$yusuan[$i]["weiyong"];
			}
			$this->assign("lamp",$lamp);
			$this->assign("yusuan",$yusuan);
			//部门预算
			$this->assign("ally",$ally);
			 $logs=$this->getlog(10,$aid);
            //print_r($logs);
            $this->assign("logs",$logs);
	        return $this->fetch();
        }
       
	}
	//作废处理
	/*public function zuofeichuli(){
		$request = Request::instance();$data = $request->post();
		$up["state"]=8;
		$up["zuofeiman"]=Session::get("employee_id");
		$up["zuofeitime"]=date("Y-m-d H:i:s");
		if(trim($data["reason"]))
			$up["zuofeireason"]=trim($data["reason"]);
		else
			return 3;
		try{
			Db::table("rc_baoxiao_apply")->where(["id"=>$data["aid"]])->update($up);
		}catch (\Exception $e){
			return 2;
		}
		return 1;
	}
	//作废
	public function zuofei($aid){
		$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
		//print_r($apply);
		$apply["cman"]=Db::table("employee")->where(["id"=>$apply["cuser"]])->value("em_name");
		$apply["ctime"]=date("Y-m-d",$apply["ctime"]);
		$tmp=Db::table("cg_kaoheqi2")->alias("k2")
		->join("cg_kaoheqi1 k1","k2.pid=k1.id")
		->join("cg_cainian c","k1.cid=c.id")
		->where("k2.id={$apply["kaohe"]}")
		->field("c.title as nian,k2.title as yue")->find();

		$apply["kaohe"]=$tmp["nian"].'-'.$tmp["yue"];
		$apply["payway"]=Db::table("cg_paymethod")->where(["id"=>$apply["payway"]])->value("title");
		$apply["bman"]=Db::table("employee")->where(["id"=>$apply["baoxiaoren"]])->value("em_name");
		$apply["jrbm"]=Db::table("cg_fijiruzd")->alias("fj")->join("department d", "fj.title=d.id")->where("fj.id={$apply["jrbm"]}")->value("d.de_name");
		if($apply["zuofeiman"]){
			$apply["zuofeiman"]=Db::table("employee")->where(["id"=>$apply["zuofeiman"]])->value("em_name");
		}else{
			$apply["zuofeiman"]="";
		}
		$feiyong=Db::table("cg_feiyongkemu3")->where("id in ({$apply["feis"]})")->select();

		$this->assign("feiyong",$feiyong);
		$feiyongnum=count($feiyong);
		$this->assign("feiyongnum",$feiyongnum);
		if($apply["chuchai"]){
			
			$apply["chuchai"]=Db::table("chuchai_apply")->where("id in ({$apply["chuchai"]})")->select();
		}
		if($apply["wanneng"]){
			
			$apply["wanneng"]=Db::table("wanneng_apply")->where("id in ({$apply["wanneng"]})")->select();
		}
		$this->assign("apply",$apply);
		$applyde=Db::table("rc_baoxiao_detail")->alias("apd")
		->join("cg_jxs j","apd.jxs=j.id","LEFT")
		->join("employee e","apd.shenpiren=e.id","LEFT")
		->where(["aid"=>$aid])
		->field("apd.start,apd.end,apd.chufa,apd.mudi,apd.feiid,apd.feis,apd.pizhunfeiyong,apd.remark,j.title as jxs,e.em_name,apd.state")
		->select();
		
		$this->assign("applyde",$applyde);
		$fujian=[];
			//print_r($apply);
			if($apply["fujian"]){
				$fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
				//print_r($fujian);
			}
		$this->assign("fujian",$fujian);
		return $this->fetch();
	}*/
	//详情
	public function detail($aid){
		$this->assign("aid",$aid);
		$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
		//print_r($apply);
		$apply["cman"]=Db::table("employee")->where(["id"=>$apply["cuser"]])->value("em_name");
		$apply["ctime"]=date("Y-m-d",$apply["ctime"]);
		$tmp=Db::table("cg_kaoheqi2")->alias("k2")
		->join("cg_kaoheqi1 k1","k2.pid=k1.id")
		->join("cg_cainian c","k1.cid=c.id")
		->where("k2.id={$apply["kaohe"]}")
		->field("c.title as nian,k2.title as yue")->find();

		$apply["kaohe"]=$tmp["nian"].'-'.$tmp["yue"];
		$apply["payway"]=Db::table("cg_paymethod")->where(["id"=>$apply["payway"]])->value("title");
		$apply["bman"]=Db::table("employee")->where(["id"=>$apply["baoxiaoren"]])->value("em_name");
		$apply["jrbm"]=Db::table("department")->where("id={$apply["jrbm"]}")->value("de_name");
		$apply["weifujin"]=$apply["pizhunjin"]-$apply["zhifujin"];
		if($apply["feis"])
			$feiyong=Db::table("cg_feiyongkemu3")->where("id in ({$apply["feis"]})")->select();
		else
			$feiyong=[];
		$this->assign("feiyong",$feiyong);
		$feiyongnum=count($feiyong);
		$this->assign("feiyongnum",$feiyongnum);
		if($apply["chuchai"]){
			
			$apply["chuchai"]=Db::table("chuchai_apply")->where("id in ({$apply["chuchai"]})")->select();
		}
		if($apply["wanneng"]){
			
			$apply["wanneng"]=Db::table("wanneng_apply")->where("id in ({$apply["wanneng"]})")->select();
		}
		$this->assign("apply",$apply);
		$applyde=Db::table("rc_baoxiao_detail")->alias("apd")
		->join("cg_jxs j","apd.jxs=j.id","LEFT")
		->join("employee e","apd.shenpiren=e.id","LEFT")
		->where(["aid"=>$aid])
		->field("apd.start,apd.end,apd.chufa,apd.mudi,apd.feiid,apd.feis,apd.pizhunfeiyong,apd.remark,j.title as jxs,e.em_name,apd.state")
		->select();
		
		$this->assign("applyde",$applyde);
		$fujian=[];
			//print_r($apply);
			if($apply["fujian"]){
				$fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
				//print_r($fujian);
			}
		$this->assign("fujian",$fujian);
		///支付
		$zhifu=Db::table("rc_baoxiao_pay")->alias("ap")
		->join("employee c","ap.cuser=c.id")
		->join("employee p","ap.zfuser=p.id")
		->where(["ap.aid"=>$aid])
		->field("c.em_name as cu,p.em_name as pu,ap.ctime,ap.zftime,ap.pzno,ap.jine,ap.remark")
		->select();
		for($i=0;$i<count($zhifu);$i++){
			$zhifu[$i]["ctime"]=date("Y-m-d",$zhifu[$i]["ctime"]);
			$zhifu[$i]["zftime"]=date("Y-m-d",$zhifu[$i]["zftime"]);
		}
		$this->assign("zhifu",$zhifu);
		 $logs=$this->getlog(10,$aid);
        //print_r($logs);
        $this->assign("logs",$logs);
		return $this->fetch();
	}
	
	public function shanchu($id){
		$res=Db::table("rc_baoxiao_apply")->where(["id"=>$id])->update(["is_deleted"=>1]);
		if($res)
			return 1;
		else
			return 0;
	}
	//申请管理页面
	public function manage($page=1,$list=10){
		$request = Request::instance();$data = $request->post();
		$state=Db::table("ti_state")->order("paixu")->select();
		$this->assign("state",$state);
		$eid=Session::get("employee_id");

		$where="ap.is_deleted=0 and ap.is_actived=1 and ap.cuser=$eid ";
		if($data){
			if(trim($data["no"])){
				$no=trim($data["no"]);
				$where.="and ap.no='$no' ";
			}
			
			if(trim($data["st"])){
				$st=trim($data["st"]);
				$where.="and ap.state=$st ";
			}
			if(trim($data["start"])){
				$start=strtotime(trim($data["start"]));
				$where.="and ap.ctime>=$start ";
			}
			if(trim($data["end"])){
				$end=strtotime(trim($data["end"]));
				$where.="and ap.ctime<=$end ";
			}
		}else{
			$data=["no"=>"","st"=>"","start"=>"","end"=>""];
		}
		$sum=Db::table("rc_baoxiao_apply")->alias("ap")
		->join("employee e","ap.cuser=e.id")
		->join("employee eb","ap.baoxiaoren=eb.id")
		->join("ti_state s","ap.state=s.id")
		->where($where)->count();
		 $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
		$apply=Db::table("rc_baoxiao_apply")->alias("ap")
		->join("employee e","ap.cuser=e.id")
		->join("employee eb","ap.baoxiaoren=eb.id")
		->join("ti_state s","ap.state=s.id")
		->where($where)->order("ap.id desc")->limit($start,$list)
		->field("ap.id,ap.no,ap.title,e.em_name as cman,eb.em_name as bman,ap.ctime,ap.pizhunjin,ap.iszhifu,ap.zhifujin,s.title as statename,ap.state")
		->select();
		for($i=0;$i<count($apply);$i++){
			$apply[$i]["ctime"]=date("Y-m-d",$apply[$i]["ctime"]);
			$apply[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$apply[$i]["id"],"ywlx"=>10])->value("id");
		}
		$this->assign("apply",$apply);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        $this->assign("data",$data);
        
		return $this->fetch();
	}
	//明细操作
	public function detailcaozuo(){
		$request = Request::instance();$data = $request->post();
		//print_r($data);exit;
		if($data["aid"]){
			if(isset($data["start"])&&isset($data["end"])&&isset($data["chufa"])&&isset($data["mudi"])&&isset($data["fei"])&&isset($data["remark"])&&isset($data["jxs"])){
				//数据数量
				$length=count($data["start"]);
				//费用处理
				$feiyonglist=[];
				for($i=0;$i<$length;$i++){
					$tmp=[];
					$flag=0;
					foreach ($data["fei"] as $key => $value) {
						$tmpde["fid"]=$key;
						if((float)$data["fei"][$key][$i]){
							$flag=1;
							$tmpde["fei"]=(float)$data["fei"][$key][$i];
						}else{
							$tmpde["fei"]=0;
						}	
						
						$tmp[]=$tmpde;
						
					}
					if($flag)
						$feiyonglist[]=$tmp;
					else{
						return json_encode(["msg"=>"每条明细中至少一条费用科目的金额数不能为空或0","state"=>2]);
					}
				}
				//print_r($feiyonglist);exit;
				//数据验证
				$adddatas=[];
				for($i=0;$i<$length;$i++){
					for($j=0;$j<count($feiyonglist[$i]);$j++){
						if($feiyonglist[$i][$j]["fei"]){
							$tmpadd=[];
							if($data["start"][$i]){
								$tmpadd["start"]=$data["start"][$i];
							}else{
								return json_encode(["msg"=>"起始日期必须填写","state"=>2]);
							}
							if($data["end"][$i]){
								$tmpadd["end"]=$data["end"][$i];
							}else{
								return json_encode(["msg"=>"结束日期必须填写","state"=>2]);
							}
							if(trim($data["chufa"][$i]))
								$tmpadd["chufa"]=trim($data["chufa"][$i]);
							else
								$tmpadd["chufa"]=null;
							if(trim($data["mudi"][$i]))
								$tmpadd["mudi"]=trim($data["mudi"][$i]);
							else
								$tmpadd["mudi"]=null;
							if(trim($data["remark"][$i]))
								$tmpadd["remark"]=trim($data["remark"][$i]);
							else
								$tmpadd["remark"]=null;
							if(trim($data["jxs"][$i]))
								$tmpadd["jxs"]=trim($data["jxs"][$i]);
							else
								$tmpadd["jxs"]=null;

							$tmpadd["feiid"]=$feiyonglist[$i][$j]["fid"];
							$tmpadd["feis"]=$feiyonglist[$i][$j]["fei"];
							$tmpadd["pizhunfeiyong"]=$feiyonglist[$i][$j]["fei"];
							$tmpadd["aid"]=$data["aid"];
							//判断预算
							
							$adddatas[]=$tmpadd;
						}
					}
					
				}
				Db::startTrans();
				try{
					//Db::Table("rc_baoxiao_detail")->where(["aid"=>$data["aid"]])->delete();
					
					$res1=Db::table("rc_baoxiao_detail")->insertAll($adddatas);
					$sumjine=Db::table("rc_baoxiao_detail")->where(["aid"=>$data["aid"]])->sum("pizhunfeiyong");
					$feiids=Db::table("rc_baoxiao_detail")->where(["aid"=>$data["aid"]])->field("distinct feiid")->select();
					$feiarr=[];
					for($i=0;$i<count($feiids);$i++){
						$feiarr[]=$feiids[$i]["feiid"];
					}
					$feiids=implode(',',$feiarr);
					$res2=Db::table("rc_baoxiao_apply")->where(["id"=>$data["aid"]])->update(["is_actived"=>1,"pizhunjin"=>$sumjine,"feis"=>$feiids]);
				}catch (\Exception $e){
					//return $e->getMessage();
					Db::rollBack();
					return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
				}
				if($res1){
					Db::commit();
					return json_encode(["msg"=>"","state"=>1]);
				}else{
					Db::rollBack();
					return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
				}
				//print_r($feiyonglist);exit;
			}else{
				return json_encode(["msg"=>"请至少添加一条明细","state"=>2]);
			}
		}else{
			return json_encode(["msg"=>"请正确提交操作","state"=>2]);
		}
	}
	public function tijiao($id){
		$yusuanres=$this->goworktest($id);
		if($yusuanres){
			if($yusuanres==1){
				return json_encode(["msg"=>"存在红灯预算，无法提交","state"=>2]);
			}else if($yusuanres==2){
				return json_encode(["msg"=>"存在红灯或黄灯预算，无法提交","state"=>2]);
			}
			//print_r($yusuanres);exit;
			$ysdata=[];
			for($i=0;$i<count($yusuanres);$i++){
				$ysdata[]=["yid"=>$yusuanres[$i]["yid"],"did"=>$yusuanres[$i]["id"],"aid"=>$id,"jine"=>$yusuanres[$i]["pizhunfeiyong"],"type"=>1];
			}
			Db::startTrans();
			try{
				$res1=Db::table("yusuan_detail")->insertAll($ysdata);
				
			}catch (\Exception $e){
					//return $e->getMessage();
				Db::rollBack();
				return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
			}
			if($res1){
				$jieguo=$this->gowork(10,$id);
				if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
					Db::commit();
					return $jieguo;
				}else{
					Db::rollBack();
					return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
				}
			}else{
				Db::rollBack();
				return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
			}
		}else{
			return json_encode(["msg"=>"存在未设定预算的明细，无法提交","state"=>2]);
		}
		//$res=Db::table("rc_baoxiao_apply")->where(["id"=>$id])->update(["state"=>3]);
		/*if($res)
			return 1;
		else
			return 0;*/
	}
	public function baocunchuli(){
		$request = Request::instance();$data = $request->post();
		$fid=10;$aid=$data["aid"];
		$num=Db::table("rc_baoxiao_detail")->where(["aid"=>$aid])->count();
			if($num){
				//验证
				if($data["jrbm"])
					$adddata["jrbm"]=$data["jrbm"];
				else
					return json_encode(["msg"=>"必须选择费用计入部门","state"=>2]);
				if($data["baoxiaoren"])
					$adddata["baoxiaoren"]=$data["baoxiaoren"];
				else
					return json_encode(["msg"=>"必须选择报销人","state"=>2]);
				if(trim($data["title"]))
					$adddata["title"]=trim($data["title"]);
				else
					return json_encode(["msg"=>"主题不能为空","state"=>2]);
				if($data["kaohe"])
					$adddata["kaohe"]=$data["kaohe"];
				if(trim($data["payway"]))
					$adddata["payway"]=trim($data["payway"]);
				else
					return json_encode(["msg"=>"支付方式必须选择","state"=>2]);
				
				if(trim($data["reason"]))
					$adddata["reason"]=trim($data["reason"]);
				else
					return json_encode(["msg"=>"报销事由不能为空","state"=>2]);
				if(isset($data["chuchai"]))
					$adddata["chuchai"]=implode(',',$data["chuchai"]);
				else
					$adddata["chuchai"]=null;
				if(isset($data["wanneng"]))
					$adddata["wanneng"]=implode(',',$data["wanneng"]);
				else
					$adddata["wanneng"]=null;
				if($data["attach"])
					$adddata["fujian"]=$data["attach"];
				else
					$adddata["fujian"]=null;
				$adddata["puser"]=Session::get("employee_id");
				$adddata["ptime"]=time();
				$adddata["state"]=3;
				Db::startTrans();
				try{
					$res2=Db::table("rc_baoxiao_apply")->where(["id"=>$data["aid"]])->update($adddata);
					
						$yusuanres=$this->goworktest($aid);
						if($yusuanres){
							if($yusuanres==1){
								Db::rollBack();
								return json_encode(["msg"=>"存在红灯预算，无法提交","state"=>2]);
							}else if($yusuanres==2){
								Db::rollBack();
								return json_encode(["msg"=>"存在红灯或黄灯预算，无法提交","state"=>2]);
							}
							$ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=3")->field("yd.id")->select();
				            if($ydid){
					            $ydids=[];
					            for($i=0;$i<count($ydid);$i++){
					               	$ydids[]=$ydid[$i]["id"];
					            }
					            $yd=implode(',',$ydids);
					            
					            Db::table("yusuan_detail")->query("delete from yusuan_detail where id in ($yd)");
					        }
							//print_r($yusuanres);exit;
							$ysdata=[];
							for($i=0;$i<count($yusuanres);$i++){
								$ysdata[]=["yid"=>$yusuanres[$i]["yid"],"did"=>$yusuanres[$i]["id"],"aid"=>$aid,"jine"=>$yusuanres[$i]["pizhunfeiyong"],"type"=>1];
							}
							
							$res1=Db::table("yusuan_detail")->insertAll($ysdata);
								
						
						
						}else{
							Db::rollBack();
							return json_encode(["msg"=>"存在未设定预算的明细，无法提交","state"=>2]);
						}
					
						if($res1&&$res2){
							$res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
							if($res["operateStatus"]=="success"){
								Db::commit();
								return json_encode(["msg"=>"","state"=>1]);
							}else{
								Db::rollBack();
								return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
							}
						}else{
							Db::rollBack();
							return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
						}
					
				}catch (\Exception $e){
					Db::rollBack();
					return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
				}
			}else{
				return json_encode(["state"=>2,"msg"=>"至少添加一条费用报销明细"]);
			}

	}
	//保存申请
	public function saveapply(){
		$request = Request::instance();$data = $request->post();
		if($data["aid"]){
			$aid=$data["aid"];
			$num=Db::table("rc_baoxiao_detail")->where(["aid"=>$aid])->count();
			if($num){
				//验证
				if($data["jrbm"])
					$adddata["jrbm"]=$data["jrbm"];
				else
					return json_encode(["msg"=>"必须选择费用计入部门","state"=>2]);
				if($data["baoxiaoren"])
					$adddata["baoxiaoren"]=$data["baoxiaoren"];
				else
					return json_encode(["msg"=>"必须选择报销人","state"=>2]);
				if(trim($data["title"]))
					$adddata["title"]=trim($data["title"]);
				else
					return json_encode(["msg"=>"主题不能为空","state"=>2]);
				if($data["kaohe"])
					$adddata["kaohe"]=$data["kaohe"];
				if(trim($data["payway"]))
					$adddata["payway"]=trim($data["payway"]);
				else
					return json_encode(["msg"=>"支付方式必须选择","state"=>2]);
				
				if(trim($data["reason"]))
					$adddata["reason"]=trim($data["reason"]);
				else
					return json_encode(["msg"=>"报销事由不能为空","state"=>2]);
				if(isset($data["chuchai"]))
					$adddata["chuchai"]=implode(',',$data["chuchai"]);
				else
					$adddata["chuchai"]=null;
				if(isset($data["wanneng"]))
					$adddata["wanneng"]=implode(',',$data["wanneng"]);
				else
					$adddata["wanneng"]=null;
				if($data["attach"])
					$adddata["fujian"]=$data["attach"];
				else
					$adddata["fujian"]=null;
				$adddata["puser"]=Session::get("employee_id");
				$adddata["ptime"]=time();
				$adddata["state"]=1;
				$adddata["is_actived"]=1;
				Db::startTrans();
				try{
					$res2=Db::table("rc_baoxiao_apply")->where(["id"=>$data["aid"]])->update($adddata);
					if($data["state"]==3){
						$yusuanres=$this->goworktest($aid);
						if($yusuanres){
							if($yusuanres==1){
								return json_encode(["msg"=>"存在红灯预算，无法提交","state"=>2]);
							}else if($yusuanres==2){
								return json_encode(["msg"=>"存在红灯或黄灯预算，无法提交","state"=>2]);
							}
							//print_r($yusuanres);exit;
							$ysdata=[];
							for($i=0;$i<count($yusuanres);$i++){
								$ysdata[]=["yid"=>$yusuanres[$i]["yid"],"did"=>$yusuanres[$i]["id"],"aid"=>$aid,"jine"=>$yusuanres[$i]["pizhunfeiyong"],"type"=>1];
							}
							
							$res1=Db::table("yusuan_detail")->insertAll($ysdata);
								
						
						
						}else{
							return json_encode(["msg"=>"存在未设定预算的明细，无法提交","state"=>2]);
						}
					}else{
						$res1=1;
					}
					
					
				}catch (\Exception $e){
					Db::rollBack();
					return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
				}
				if($res1&&$res2){
					if($data["state"]==3){
						$jieguo=$this->gowork(10,$aid);
								if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
									Db::commit();
									return $jieguo;
								}else{
									Db::rollBack();
									return $jieguo;
								}
					}else{
						Db::commit();
						return json_encode(['state'=>1,'msg'=>'提交成功']);
					}
					
				}else{
					Db::rollBack();
					return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
				}
			}else{
				return json_encode(["msg"=>"至少成功添加一条明细","state"=>2]);
			}
		}else{
			return json_encode(["msg"=>"请正确提交操作","state"=>2]);
		}
		
	}
	//主表操作
	public function addmain(){
		$request = Request::instance();$data = $request->post();
		//print_r($data);exit;
		//验证
		if($data["jrbm"])
			$adddata["jrbm"]=$data["jrbm"];
		else
			return json_encode(["msg"=>"必须选择费用计入部门","state"=>2]);
		if($data["baoxiaoren"])
			$adddata["baoxiaoren"]=$data["baoxiaoren"];
		else
			return json_encode(["msg"=>"必须选择报销人","state"=>2]);
		if(trim($data["title"]))
			$adddata["title"]=trim($data["title"]);
		else
			return json_encode(["msg"=>"主题不能为空","state"=>2]);
		if($data["kaohe"])
			$adddata["kaohe"]=$data["kaohe"];
		if(trim($data["payway"]))
			$adddata["payway"]=trim($data["payway"]);
		else
			return json_encode(["msg"=>"支付方式必须选择","state"=>2]);
		if(!trim($data["feis"]))
			return json_encode(["msg"=>"至少选择一个三级科目","state"=>2]);
		if(trim($data["reason"]))
			$adddata["reason"]=trim($data["reason"]);
		else
			return json_encode(["msg"=>"报销事由不能为空","state"=>2]);
		if(isset($data["chuchai"]))
			$adddata["chuchai"]=implode(',',$data["chuchai"]);
		else
			$adddata["chuchai"]=null;
		if(isset($data["wanneng"]))
			$adddata["wanneng"]=implode(',',$data["wanneng"]);
		else
			$adddata["wanneng"]=null;
		if($data["attach"])
			$adddata["fujian"]=$data["attach"];
		else
			$adddata["fujian"]=null;

		if($data["aid"]){
			$adddata["puser"]=Session::get("employee_id");
			$adddata["ptime"]=time();
			try{
				$res1=Db::table("rc_baoxiao_apply")->where(["id"=>$data["aid"]])->update($adddata);
				$aid=$data["aid"];
			}catch (\Exception $e){
				return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
			}
			
		}else{
			 //生成单号
	            $timenow=date("Ymd");
	            $num=Db::table("rc_baoxiao_apply")->where("no like '$timenow%'")->count();
	            $num++;
	            $strnum=$timenow.sprintf("%05d", $num);
	            $adddata["no"]=$strnum;
	            $adddata["cuser"]=Session::get("employee_id");
	            $adddata["puser"]=Session::get("employee_id");
	            $adddata["ctime"]=time();
	            $adddata["ptime"]=time();

	            try{
	            	$res1=Db::table("rc_baoxiao_apply")->insertGetId($adddata);
	            	$aid=$res1;
	            }catch (\Exception $e){
	            	return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	            }
		}
		if($res1){
			return json_encode(["msg"=>$aid,"state"=>1]);
		}else{
			return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
		}
	}
	//添加申请行
	public function addmx($aid,$feis){
		$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
		$feiyong=Db::table("cg_feiyongkemu3")->where("id in ($feis)")->select();
		$str="";
		for($i=0;$i<count($feiyong);$i++){
			$str.='<td style="min-width: 100px;width: 100px"><input type="text" name="fei['.$feiyong[$i]["id"].'][]" style="width:95px;" class="form-control num"></td>';
		}
		echo <<<EOF
 <tr>
                <td><button type="button" class="btn btn-sm btn-danger delthis">删除</button></td>
                <td style="min-width: 130px;width: 130px"><input type="text" name="start[]" class="form-control layer-date start" style="width: 90%" ></td>
                 <td style="min-width: 130px;width: 130px"> <input type="text" name="end[]" class="form-control  layer-date end" style="width: 90%" ></td>
                 <td style="min-width: 250px;width: 250px" >
                      <div class="container-fluid">
                            <div class="row">
                                <div class="col-xs-8">
                                    <div class="input-group"  >
                                        <input type="text" placeholder="请输入关键字或空格查询" class="chufa form-control"  name="chufa[]" value="">
                                        <div class="input-group-btn">
                                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                                <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                            </ul>
                                        </div>
                                    </div>
                                    <div class="selectedOnlyOne " style="display: none;" >
                                      
                                        <span class="inin"></span>
                                        <span class="close">×</span>
                                    </div>
                                </div>
                               <div class="col-xs-4">
                                <button class="btn btn-primary select_chufa" type="button" >选择</button>
                            </div>
                           </div>
                        </div>
                 </td>
                  <td style="min-width: 250px;width: 250px" >
                      <div class="container-fluid">
                            <div class="row">
                                <div class="col-xs-8">
                                    <div class="input-group"  >
                                        <input type="text" placeholder="请输入关键字或空格查询" class="chufa form-control"  name="mudi[]" value="">
                                        <div class="input-group-btn">
                                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                                <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                            </ul>
                                        </div>
                                    </div>
                                    <div class="selectedOnlyOne " style="display: none;" >
                                      
                                        <span class="inin"></span>
                                        <span class="close">×</span>
                                    </div>
                                </div>
                               <div class="col-xs-4">
                                <button class="btn btn-primary select_chufa" type="button" >选择</button>
                            </div>
                           </div>
                        </div>
                 </td>
                	{$str}
                  <td style="min-width: 200px;width: 200px"><input type="text" name="remark[]" class="form-control" style="width: 90%"></td>
                 <td style="min-width: 250px;width: 250px" >
                      <div >
                       
                            <div class="row">
                                <div class="col-xs-8">
                                    <div class="input-group cusName_input"   >
                                        <input type="text" placeholder="请输入关键字或空格查询" class="form-control cusName" name="jxs[]" >
                                        <div class="input-group-btn">
                                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                                <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                            </ul>
                                        </div>
                                    </div>

                                    <div  class="selectedOnlyOne cusName_queding" style="display: none;">
                                       
                                        <span class="inin"></span>
                                        <span class="close">×</span>
                                    </div>
                                </div>
                                  <div class="col-xs-4">
                                    <button class="btn btn-primary select_jxs" type="button" >选择</button>
                                </div>
                            </div>
                 </td>
            </tr>
EOF;
	}
	//添加申请明细
	public function adddetail($aid,$feis){
		//echo $feis;
		$this->assign("aid",$aid);$this->assign("feis",$feis);
		$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
		//$applyde=Db::table("rc_baoxiao_detail")->where(["aid"=>$aid])->select();
		$feiyong=Db::table("cg_feiyongkemu3")->where("id in ($feis)")->select();

		
		$this->assign("feiyong",$feiyong);
		$this->assign("apply",$apply);
		//$this->assign("applyde",$applyde);
		return $this->fetch();
	}
	//删除明细
	public function shanchumx($id){
		try{
			$aid=Db::table("rc_baoxiao_detail")->where(["id"=>$id])->value("aid");
			$res=Db::table("rc_baoxiao_detail")->where(["id"=>$id])->delete();
			$sumjine=Db::table("rc_baoxiao_detail")->where(["aid"=>$aid])->sum("pizhunfeiyong");
			$feiids=Db::table("rc_baoxiao_detail")->where(["aid"=>$aid])->field("distinct feiid")->select();
			$feiarr=[];
			for($i=0;$i<count($feiids);$i++){
				$feiarr[]=$feiids[$i]["feiid"];
			}
			$feiids=implode(',',$feiarr);
			$res1=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->update(["state"=>1,"is_actived"=>1,"pizhunjin"=>$sumjine,"feis"=>$feiids]);
		}catch (\Exception $e){
	        return 2;
	    }
	    if($res)
	    	return 1;
	    else
	    	return 2;
	}
	//添加申请
	public function add($aid=null){
		//echo $aid;exit;
		$this->assign("aid",$aid);
		$pay=Db::table("cg_paymethod")->select();
		$isno=db("system_param")->where("k='isNo'")->value("v");
		$this->assign("isno",$isno);
		$this->assign("pay",$pay);
		$myeid=session("employee_id");
		$mydep=db("department_employee de")->join("department d","de.department_id=d.id")->where("de.index=1 and de.employee_id=$myeid")->field("d.id,d.de_name")->find();
		$this->assign("mydep",$mydep);
		if($aid){
			$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
			$this->assign("apply",$apply);
			$eid=$apply["cuser"];
			$ctime=date("Y-m-d H:i:s",$apply["ctime"]);
			$jrbm=Db::table("department")->where("id={$apply["jrbm"]}")->value("de_name");
			$this->assign("jrbm",$jrbm);
			$baoxiaoren=Db::table("employee")->where(["id"=>$apply["baoxiaoren"]])->value("em_name");
			$this->assign("baoxiaoren",$baoxiaoren);
			$nowc=$apply["ctime"];
			$feiids=Db::table("rc_baoxiao_detail")->where(["aid"=>$aid])->field("distinct feiid")->select();
					$feiarr=[];
					for($i=0;$i<count($feiids);$i++){
						$feiarr[]=$feiids[$i]["feiid"];
			}
			$feiids=implode(',',$feiarr);
			if($feiids)
				$feiyong=Db::table("cg_feiyongkemu3")->where("id in ({$feiids})")->select();
			else 
				$feiyong=[];
			$this->assign("feiyong",$feiyong);
			$haschuchai=explode(',',$apply["chuchai"]);
			$haswanneng=explode(',',$apply["wanneng"]);
			$fujian=[];
			//print_r($apply);
			if($apply["fujian"]){
				$fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
				//print_r($fujian);
			}
			$detail=Db::table("rc_baoxiao_detail")->alias("rc")->join("cg_jxs j","rc.jxs=j.id","LEFT")
			->where("rc.aid=$aid")->order("rc.id")->field("rc.id,rc.start,rc.end,rc.chufa,rc.mudi,rc.feis,rc.pizhunfeiyong,rc.feiid,rc.remark,j.title as jxs")->select();
			
			//预算处理
			//获取当前预算格式
			$tr=Db::table("target_format")->where(["type_id"=>4])->find();
			for($i=0;$i<count($detail);$i++){

				if($tr){
					$erjikaoheqi=$apply["kaohe"];
					$yijikaoheqi=Db::table("cg_kaoheqi2")->where(["id"=>$erjikaoheqi])->value("pid");
					$depart=$apply["jrbm"];
					$sanjifeiyong=$detail[$i]["feiid"];
					$erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
					$yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
					$where="yijikaoheqi=$yijikaoheqi and type=3 ";
					if($tr["depart_id"]){
						$where.="and depart={$depart} ";
					}else{
						$where.="and depart is null ";
					}
					if($tr["kaoheqi"]==18){
						$where.="and erjikaoheqi=$erjikaoheqi ";
					}else{
						$where.="and erjikaoheqi is null ";
					}
					if($tr["feiyong_id"]){
						if($tr["feiyong_id"]==16){
							$where.="and sanjifeiyong=$sanjifeiyong ";
						}else if($tr["feiyong_id"]==15){
							$where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
						}else{
							$where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
						}
					}else{
						$where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
					}
					//echo $where;
					$yusuan=Db::table("yusuan")->where($where)->find();
					if($yusuan){
						$detail[$i]["yid"]=$yusuan["id"];
						$zongyusuan=$yusuan["jine"];
						$pizhun=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>2])->sum("jine");
						if(!$pizhun)
							$pizhun=0;
						$inapply=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>1])->sum("jine");
						if(!$inapply)
							$inapply=0;
						if($zongyusuan>=$pizhun+$inapply){
							$detail[$i]["ytype"]=1;
						}else if($zongyusuan<$pizhun){
							$detail[$i]["ytype"]=3;
						}else{
							$detail[$i]["ytype"]=2;
						}
					}else{
						$detail[$i]["yid"]=null;
						$detail[$i]["ytype"]=0;
					}
				}else{
					$detail[$i]["yid"]=null;
					$detail[$i]["ytype"]=0;
				}
				
			}
			$this->assign("detail",$detail);
		}else{
			//申请人
			$eid=Session::get("employee_id");
			$ename=db("employee")->where(["id"=>$eid])->value("em_name");
			$ctime=date("Y-m-d H:i:s");
			$fujian=[];
			$nowc=time();
			$haschuchai=[];
			$haswanneng=[];
			$title=date("Y-m-d{$ename}报销申请单");
			
			$this->assign("title",$title);
		}

		$cuser=Db::table("employee")->where(["id"=>$eid])->find();
		$this->assign("cuser",$cuser);

		$this->assign("ctime",$ctime);
		$this->assign("fujian",$fujian);
		//查询三月内出差申请
		$starttime=strtotime("-3 month");
		$chuchai=Db::table("chuchai_apply")->where("cuser=$eid and ctime>$starttime and is_deleted=0 and state=7")->select();
		for($i=0;$i<count($chuchai);$i++){
			$chuchai[$i]["ischeck"]=0;
			for($j=0;$j<count($haschuchai);$j++){
				if($chuchai[$i]["id"]==$haschuchai[$j]){
					$chuchai[$i]["ischeck"]=1;break;
				}
			}
		}
		$this->assign("chuchai",$chuchai);
		$wanneng=Db::table("wanneng_apply")->where("cuser=$eid and ctime>$starttime and is_deleted=0 and state=7 and iscost=1")->select();
		for($i=0;$i<count($wanneng);$i++){
			$wanneng[$i]["ischeck"]=0;
			for($j=0;$j<count($haswanneng);$j++){
				if($wanneng[$i]["id"]==$haswanneng[$j]){
					$wanneng[$i]["ischeck"]=1;break;
				}
			}
		}
		$this->assign("wanneng",$wanneng);
		//报销归入考核期
		
		$kaohe=Db::table("cg_kaoheqi2")->alias("k2")
		->join("cg_kaoheqi1 k1","k2.pid=k1.id")
		->join("cg_cainian c","k1.cid=c.id")
		->where("k2.endtime>=$nowc")
		->order("k2.starttime")
		->limit(0,5)
		->field("k2.id,k2.title as yue,c.title as nian")
		->select();
		//print_r($kaohe);
		$this->assign("kaohe",$kaohe);
		return $this->fetch();
	}
	//添加申请明细
	public function zuofeidetail($aid,$feis,$from){
		//echo $feis;
		$this->assign("aid",$aid);$this->assign("feis",$feis);$this->assign("from",$from);
		$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
		//$applyde=Db::table("rc_baoxiao_detail")->where(["aid"=>$aid])->select();
		$feiyong=Db::table("cg_feiyongkemu3")->where("id in ($feis)")->select();

		
		$this->assign("feiyong",$feiyong);
		$this->assign("apply",$apply);
		//$this->assign("applyde",$applyde);
		return $this->fetch();
	}

	public function zuofeichuli(){
		$request = Request::instance();$data = $request->post();
		
		
      	//print_r($data);exit;
      	$fid=10;$aid=$data["aid"];$feireason=$data["feireason"];
      	if(!trim($feireason))
        	return json_encode(["msg"=>"作废原因不能为空","state"=>2]);
    	else{
    		$res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
    		if($res["operateStatus"]=="success"){
    			$ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=3")->field("yd.id")->select();
	            if($ydid){
		            $ydids=[];
		            for($i=0;$i<count($ydid);$i++){
		               	$ydids[]=$ydid[$i]["id"];
		            }
		            $yd=implode(',',$ydids);
		            try{
		              	Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
		              	 	$up["zuofeiman"]=Session::get("employee_id");
					        $up["zuofeitime"]=time();
					        $up["zuofeireason"]=$feireason;
					        $up["id"]=$aid;
					        $up["state"]=8;
					    Db::table("rc_baoxiao_apply")->update($up);
		            }catch (\Exception $e){
        
				          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
				        }
				      return json_encode(["msg"=>"","state"=>1]);
	              
    				}		
    	}else{
        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
      }
      
	}
}
	function zuofei($aid,$from=1){
		$this->assign("from",$from);
		$this->assign("aid",$aid);
		$pay=Db::table("cg_paymethod")->select();

		$this->assign("pay",$pay);
		if($aid){
			$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
			$this->assign("apply",$apply);
			$eid=$apply["cuser"];
			$ctime=date("Y-m-d H:i:s",$apply["ctime"]);
			$apply["jrbm"]=Db::table("department")->where("id={$apply["jrbm"]}")->value("de_name");
			$this->assign("jrbm",$jrbm);
			$baoxiaoren=Db::table("employee")->where(["id"=>$apply["baoxiaoren"]])->value("em_name");
			$this->assign("baoxiaoren",$baoxiaoren);
			$nowc=$apply["ctime"];
			$feiids=Db::table("rc_baoxiao_detail")->where(["aid"=>$aid])->field("distinct feiid")->select();
					$feiarr=[];
					for($i=0;$i<count($feiids);$i++){
						$feiarr[]=$feiids[$i]["feiid"];
			}
			$feiids=implode(',',$feiarr);
			if($feiids)
				$feiyong=Db::table("cg_feiyongkemu3")->where("id in ({$feiids})")->select();
			else 
				$feiyong=[];
			$this->assign("feiyong",$feiyong);
			$haschuchai=explode(',',$apply["chuchai"]);
			$haswanneng=explode(',',$apply["wanneng"]);
			$fujian=[];
			//print_r($apply);
			if($apply["fujian"]){
				$fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
				//print_r($fujian);
			}
			$detail=Db::table("rc_baoxiao_detail")->alias("rc")->join("cg_jxs j","rc.jxs=j.id","LEFT")
			->where("rc.aid=$aid")->order("rc.id")->field("rc.id,rc.start,rc.end,rc.chufa,rc.mudi,rc.feis,rc.pizhunfeiyong,rc.feiid,rc.remark,j.title as jxs")->select();
			
			//预算处理
			//获取当前预算格式
			$tr=Db::table("target_format")->where(["type_id"=>4])->find();
			for($i=0;$i<count($detail);$i++){

				if($tr){
					$erjikaoheqi=$apply["kaohe"];
					$yijikaoheqi=Db::table("cg_kaoheqi2")->where(["id"=>$erjikaoheqi])->value("pid");
					$depart=$jrbm;
					$sanjifeiyong=$detail[$i]["feiid"];
					$erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
					$yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
					$where="yijikaoheqi=$yijikaoheqi and type=3 ";
					if($tr["depart_id"]){
						$where.="and depart={$depart} ";
					}else{
						$where.="and depart is null ";
					}
					if($tr["kaoheqi"]==18){
						$where.="and erjikaoheqi=$erjikaoheqi ";
					}else{
						$where.="and erjikaoheqi is null ";
					}
					if($tr["feiyong_id"]){
						if($tr["feiyong_id"]==16){
							$where.="and sanjifeiyong=$sanjifeiyong ";
						}else if($tr["feiyong_id"]==15){
							$where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
						}else{
							$where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
						}
					}else{
						$where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
					}
					//echo $where;
					$yusuan=Db::table("yusuan")->where($where)->find();
					if($yusuan){
						$detail[$i]["yid"]=$yusuan["id"];
						$zongyusuan=$yusuan["jine"];
						$pizhun=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>2])->sum("jine");
						if(!$pizhun)
							$pizhun=0;
						$inapply=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>1])->sum("jine");
						if(!$inapply)
							$inapply=0;
						if($zongyusuan>=$pizhun+$inapply){
							$detail[$i]["ytype"]=1;
						}else if($zongyusuan<$pizhun){
							$detail[$i]["ytype"]=3;
						}else{
							$detail[$i]["ytype"]=2;
						}
					}else{
						$detail[$i]["yid"]=null;
						$detail[$i]["ytype"]=0;
					}
				}else{
					$detail[$i]["yid"]=null;
					$detail[$i]["ytype"]=0;
				}
				
			}
			$this->assign("detail",$detail);
		}else{
			//申请人
			$eid=Session::get("employee_id");
			$ctime=date("Y-m-d H:i:s");
			$fujian=[];
			$nowc=time();
			$haschuchai=[];
			$haswanneng=[];
		}

		$cuser=Db::table("employee")->where(["id"=>$eid])->find();
		$this->assign("cuser",$cuser);
		$this->assign("ctime",$ctime);
		$this->assign("fujian",$fujian);
		//查询三月内出差申请
		$starttime=strtotime("-3 month");
		$chuchai=Db::table("chuchai_apply")->where("cuser=$eid and ctime>$starttime and is_deleted=0 and state=7")->select();
		for($i=0;$i<count($chuchai);$i++){
			$chuchai[$i]["ischeck"]=0;
			for($j=0;$j<count($haschuchai);$j++){
				if($chuchai[$i]["id"]==$haschuchai[$j]){
					$chuchai[$i]["ischeck"]=1;break;
				}
			}
		}
		$this->assign("chuchai",$chuchai);
		$wanneng=Db::table("wanneng_apply")->where("cuser=$eid and ctime>$starttime and is_deleted=0 and state=7 and iscost=1")->select();
		for($i=0;$i<count($wanneng);$i++){
			$wanneng[$i]["ischeck"]=0;
			for($j=0;$j<count($haswanneng);$j++){
				if($wanneng[$i]["id"]==$haswanneng[$j]){
					$wanneng[$i]["ischeck"]=1;break;
				}
			}
		}
		$this->assign("wanneng",$wanneng);
		//报销归入考核期
		
		$kaohe=Db::table("cg_kaoheqi2")->alias("k2")
		->join("cg_kaoheqi1 k1","k2.pid=k1.id")
		->join("cg_cainian c","k1.cid=c.id")
		->where("k2.endtime>=$nowc")
		->order("k2.starttime")
		->limit(0,5)
		->field("k2.id,k2.title as yue,c.title as nian")
		->select();
		//print_r($kaohe);
		$this->assign("kaohe",$kaohe);
		$btn=$this->getbton(10,$aid);
        $this->assign("btn",$btn);
        $logs=$this->getlog(10,$aid);
        //print_r($logs);
        $this->assign("logs",$logs);
		return $this->fetch();
	}
	//提交前预算验证
	public function goworktest($aid){
		//暂行版本超预算可申请，未预算不可申请
		$tr=Db::table("target_format")->where(["type_id"=>4])->find();
		$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
		$detail=Db::table("rc_baoxiao_detail")->alias("rc")->join("cg_jxs j","rc.jxs=j.id","LEFT")
			->where("rc.aid=$aid")->order("rc.id")->field("rc.id,rc.feiid,rc.pizhunfeiyong")->select();
		$isyellow=0;
		$isred=0;
		for($i=0;$i<count($detail);$i++){

				if($tr){
					$erjikaoheqi=$apply["kaohe"];
					$yijikaoheqi=Db::table("cg_kaoheqi2")->where(["id"=>$erjikaoheqi])->value("pid");
					$depart=$apply["jrbm"];
					$sanjifeiyong=$detail[$i]["feiid"];
					$erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
					$yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
					$where="yijikaoheqi=$yijikaoheqi and type=3 ";
					if($tr["depart_id"]){
						$where.="and depart={$depart} ";
					}else{
						$where.="and depart is null ";
					}
					if($tr["kaoheqi"]==18){
						$where.="and erjikaoheqi=$erjikaoheqi ";
					}else{
						$where.="and erjikaoheqi is null ";
					}
					if($tr["feiyong_id"]){
						if($tr["feiyong_id"]==16){
							$where.="and sanjifeiyong=$sanjifeiyong ";
						}else if($tr["feiyong_id"]==15){
							$where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
						}else{
							$where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
						}
					}else{
						$where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
					}
					//echo $where;
					$yusuan=Db::table("yusuan")->where($where)->find();
					if($yusuan){
						$detail[$i]["yid"]=$yusuan["id"];
						$zongyusuan=$yusuan["jine"];
						$pizhun=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>2])->sum("jine");
						if(!$pizhun)
							$pizhun=0;
						$inapply=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>1])->sum("jine");
						if(!$inapply)
							$inapply=0;
						if($zongyusuan>=$pizhun+$inapply){
							$detail[$i]["ytype"]=1;
						}else if($zongyusuan<$pizhun){
							$detail[$i]["ytype"]=3;
							$isred=1;
						}else{
							$detail[$i]["ytype"]=2;
							$isyellow=1;
						}
					}else{
						return 0;
					}
				}else{
					return 0;
				}
				
			}
			$lamp=db("system_param")->where("k='lamp'")->value("v");
			//1red  2yellow  3no
			if($lamp==1){
				if($isred==1){
					return 1;
				}
			}else if($lamp==2){
				if($isyellow==1){
					return 2;
				}
			}


			return $detail;
	}
	public function getysformat($yid){
		$ys=db("yusuan")->where(["id"=>$yid])->find();
		$data=[];
		//部门
		if($ys["depart"]){
			$data["bumen"]=$ys["depart"];
		}else{
			$data["bumen"]="";
		}
		//费用科目
		if($ys["sanjifeiyong"]){
			$data["kemu"]=3;
			$data["erjifeiyong"]="";$data["yijifeiyong"]="";
			$data["sanjifeiyong"]=$ys["sanjifeiyong"];
		}else if($ys["erjifeiyong"]){
			$data["sanjifeiyong"]="";$data["yijifeiyong"]="";
			$data["kemu"]=2;
			$data["erjifeiyong"]=$ys["erjifeiyong"];
		}else{
			$data["sanjifeiyong"]="";$data["erjifeiyong"]="";
			$data["kemu"]=1;
			if($ys["yijifeiyong"])
				$data["yijifeiyong"]=$ys["yijifeiyong"];
			else
				$data["yijifeiyong"]="";
		}
		//考核期
		$data["cid"]=$ys["cainian"];
		if($ys["erjikaoheqi"]){
			$data["cainian"]=2;
			$data["yijikaoheqi"]="";
			$data["erjikaoheqi"]=$ys["erjikaoheqi"];
		}
		if($ys["yijikaoheqi"]){
			$data["cainian"]=1;
			$data["yijikaoheqi"]=$ys["yijikaoheqi"];
			$data["erjikaoheqi"]="";
		}
		return json_encode($data);
	}
	public function yusuantongbu($aid,$jrbm,$kaohe){
		$tr=Db::table("target_format")->where(["type_id"=>4])->find();
		$apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
		$detail=Db::table("rc_baoxiao_detail")->alias("rc")->join("cg_jxs j","rc.jxs=j.id","LEFT")
			->where("rc.aid=$aid")->order("rc.id")->field("rc.id,rc.feiid")->select();
		for($i=0;$i<count($detail);$i++){

				if($tr){
					$erjikaoheqi=$kaohe;
					$yijikaoheqi=Db::table("cg_kaoheqi2")->where(["id"=>$erjikaoheqi])->value("pid");
					$depart=$jrbm;
					$sanjifeiyong=$detail[$i]["feiid"];
					$erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
					$yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
					$where="yijikaoheqi=$yijikaoheqi and type=3 ";
					if($tr["depart_id"]){
						$where.="and depart={$depart} ";
					}else{
						$where.="and depart is null ";
					}
					if($tr["kaoheqi"]==18){
						$where.="and erjikaoheqi=$erjikaoheqi ";
					}else{
						$where.="and erjikaoheqi is null and yijikaoheqi=$yijikaoheqi ";
					}
					if($tr["feiyong_id"]){
						if($tr["feiyong_id"]==16){
							$where.="and sanjifeiyong=$sanjifeiyong ";
						}else if($tr["feiyong_id"]==15){
							$where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
						}else{
							$where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
						}
					}else{
						$where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
					}
					//echo $where;
					$yusuan=Db::table("yusuan")->where($where)->find();
					if($yusuan){
						$detail[$i]["yid"]=$yusuan["id"];
						$zongyusuan=$yusuan["jine"];
						$pizhun=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>2])->sum("jine");
						if(!$pizhun)
							$pizhun=0;
						$inapply=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>1])->sum("jine");
						if(!$inapply)
							$inapply=0;
						if($zongyusuan>=$pizhun+$inapply){
							$detail[$i]["ytype"]=1;
						}else if($zongyusuan<$pizhun){
							$detail[$i]["ytype"]=3;
						}else{
							$detail[$i]["ytype"]=2;
						}
					}else{
						$detail[$i]["yid"]=0;
						$detail[$i]["ytype"]=0;
					}
				}else{
					$detail[$i]["yid"]=o;
					$detail[$i]["ytype"]=0;
				}
				
			}
			return json_encode($detail);
	}
	 //suggest查找费用科目3
	
    public function feiyongkemu3json(){;
       $where = "esuseway like '%\"4\"%'";
        $data = Db::table('cg_feiyongkemu3')->field('title,id')->where($where)->select();
//        echo Db::table('cg_feiyon"esuseway like '%\"4\"%'"gkemku3')->getLastSql();
        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    public function selectfei(){
    	return $this->fetch();
    }
    public function feitree(){
    	 $where = "esuseway like '%\"4\"%'";
       $data = Db::table('cg_feiyongkemu3')->field('title,id')->where($where)->select();	
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            $temp['id'] = $v['id'];
            
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }
     //suggest查找地区
    public function cityjson(){
       $where=[];
        $data = Db::table('cg_county')->field('title,id')->where($where)->select();
//        echo Db::table('cg_feiyon"esuseway like '%\"4\"%'"gkemku3')->getLastSql();
        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
     //授权区域
    public function sqqy(){
        return $this->fetch();
    }

    //授权区域树
    public function sqqyTree(){
        $data = db('cg_provice')->field('id,title name')->select();
        foreach($data as $k=>$v){
            $city = db('cg_city')->where('provice',$v['id'])->field('id,title name')->select();
            foreach($city as $k1=>$v1){
                $v1['children'] = db('cg_county')->where('city',$v1['id'])->field('id,title name')->select();
                $city[$k1] = $v1;
            }
            $v['children'] = $city;
            $data[$k] = $v;
        }
       // print_r($data);exit;
        echo json_encode($data);
    }
    public function selectjrbm()
    {
        return $this->fetch();
    }
}